﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using umbraco.cms.businesslogic;
using umbraco.cms.businesslogic.web;

namespace AutoFolders.Providers
{
    public abstract class BaseFolderProvider : IFolderProvider
    {
        private Dictionary<string, string> m_properties = new Dictionary<string, string>();

        public virtual Dictionary<string, string> Properties
        { 
            get { return m_properties; }
        }

        public virtual string TruncatedFolderUrl { get; set; }
        public virtual string RootFolder { get; set; }
        public abstract int FindValidFolderId(Document newDocument, int iNodeRootFolder);
        public abstract int CreateFolderStructure(Document newDocument, int iNodeRootFolder, string folderDocTypeAlias);
        public abstract int CreatedFolderDepth { get; }

        public virtual string NiceUrl(string realUrl)
        {
            if (!String.IsNullOrEmpty(TruncatedFolderUrl))
            {
                int additionFolders = this.CreatedFolderDepth;
                List<string> urlParts = new List<string>(realUrl.Split('/'));
                if (urlParts.Count > (additionFolders + 1))
                {
                    while (additionFolders > 0)
                    {
                        urlParts.RemoveAt(urlParts.Count - 2);
                        additionFolders--;
                    }
                }
                string truncatedUrl = "";

                foreach (string part in urlParts)
                {
                    if (truncatedUrl.Length > 0)
                        truncatedUrl += "/";

                    truncatedUrl += part;
                }

                return "/" + truncatedUrl;
            }
            else
            {
                return realUrl;
            }
        }
    }
}
